package com.hxs.hxsserver.common;

import com.github.dozermapper.core.CustomConverter;
import com.github.dozermapper.core.MappingException;

import java.util.Arrays;

/**
 * @author Andi
 */
public class EnumConverter implements CustomConverter {
    @Override
    public Object convert(Object dest, Object src, Class<?> destClass, Class<?> srcClass) {
        if (src == null) {
            return null;
        }

        if (srcClass.isEnum() && src instanceof Option) {
            Option option = (Option) src;
            return new OptionDto(option.origin(), ((Enum) src).name(), option.label());
        }
        if (src instanceof OptionDto && destClass.isEnum()) {
            OptionDto dto = (OptionDto) src;
            return Arrays.stream(destClass.getEnumConstants())
                    .filter(it -> ((Enum) it).name().equalsIgnoreCase(dto.getName()))
                    .findFirst()
                    .orElse(null);
        }
        throw new MappingException(String.format("can not mapping %s to %s", srcClass.getName(), destClass.getName()));
    }
}
